package com.zzyl.nursing.service.impl;

import java.util.ArrayList;
import java.util.List;


import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
/**
 * 入住Service业务层处理
 * 
 * @author fhy
 * @date 2025-10-10
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper,CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private BedMapper bedMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return save(checkIn)?1:0;
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return updateById(checkIn)?1:0;
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids))?1:0;
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return removeById(id)?1:0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int apply(CheckInApplyDto dto) {
        CheckInConfigDto checkInConfigDto = dto.getCheckInConfigDto();
        CheckInContractDto checkInContractDto = dto.getCheckInContractDto();
        List<ElderFamilyDto> elderFamilyDtoList = dto.getElderFamilyDtoList();
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
//校验老人是否已入住  如果已入住直接抛异常BaseException
//根据老人身份证号+状态状态（0：禁用，1:启用  2:请假 3:退住中 4入住中 5已退住）  从老人表中查询
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo , checkInElderDto.getIdCardNo());
        queryWrapper.eq(Elder::getStatus,4);
        Elder elder = elderMapper.selectOne(queryWrapper);
        if (elder!=null){
            throw new BaseException("该老人已入住");
        }
        //更新床位的状态
        Long bedId = checkInConfigDto.getBedId();
        Bed bed = bedMapper.selectById(bedId);
        if (bed==null){
            throw new BaseException("请选择正确的床位");
        }
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //新增或更新老人elder
        elder = saveOrUpdateElder(checkInElderDto,bed);
        //新增合同信息  合同号要求： HT+18位数字，例：HT202501011012590001
        saveContract(checkInContractDto,elder,checkInConfigDto);
        //新增入住信息  老人家属信息存到remark字段中
        CheckIn checkIn = saveCheckIn(elder,checkInConfigDto,elderFamilyDtoList);
        //新增入住配置
        saveCheckInConfig(checkInContractDto,elder,checkInConfigDto,checkIn);

        return 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckIn checkIn = checkInMapper.selectById(id);
        if (checkIn == null){
            throw new BaseException("老头不存在");
        }
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        CheckInElderVo elderVo = new CheckInElderVo();
//        elderVo.setId(elder.getId());
//        elderVo.setName(elder.getName());
//        elderVo.setIdCardNo(elder.getIdCardNo());
//        elderVo.setBirthday(elder.getBirthday());
//        elderVo.setSex(elder.getSex());
//        elderVo.setPhone(elder.getPhone());
//        elderVo.setAddress(elder.getAddress());
//        elderVo.setImage(elder.getImage());
//        elderVo.setIdCardNationalEmblemImg(elder.getIdCardNationalEmblemImg());
//        elderVo.setIdCardPortraitImg(elder.getIdCardPortraitImg());
        int age = DateUtil.ageOfNow(elder.getBirthday());
        elderVo.setAge(age);
          BeanUtils.copyProperties(elder, elderVo);
          List<ElderFamilyVo> list = new ArrayList<>();
          list = JSONUtil.toList(JSONUtil.parseArray(checkIn.getRemark()), ElderFamilyVo.class);
          LambdaQueryWrapper<CheckInConfig> queryWrapper = new LambdaQueryWrapper<>();
          queryWrapper.eq(CheckInConfig::getCheckInId,id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(queryWrapper);
        CheckInConfigVo configVo = new CheckInConfigVo();
        configVo.setStartDate(checkIn.getStartDate());
        configVo.setEndDate(checkIn.getEndDate());
        configVo.setBedNumber(checkIn.getBedNumber());
        BeanUtils.copyProperties(checkInConfig, configVo);

        LambdaQueryWrapper<Contract> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.eq(Contract::getElderId,checkIn.getElderId());
        Contract contract = contractMapper.selectOne(queryWrapper1);
        CheckInDetailVo check = new CheckInDetailVo();
        check.setCheckInConfigVo(configVo);
        check.setCheckInElderVo(elderVo);
        check.setContract(contract);
        check.setElderFamilyVoList(list);


        return check;
    }

    private Elder saveOrUpdateElder(CheckInElderDto checkInElderDto, Bed bed) {
        LambdaQueryWrapper<Elder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Elder::getIdCardNo,checkInElderDto.getIdCardNo());
        Elder elder = elderMapper.selectOne(queryWrapper);
        if(elder==null){
            elder = new Elder();
            elder.setName(checkInElderDto.getName());
            elder.setImage(checkInElderDto.getImage());
            elder.setIdCardNo(checkInElderDto.getIdCardNo());
            elder.setSex(checkInElderDto.getSex());
            elder.setStatus(4);   //状态（0：禁用，1:启用  2:请假 3:退住中 4入住中 5已退住）
            elder.setPhone(checkInElderDto.getPhone());
            elder.setBirthday(checkInElderDto.getBirthday());
            elder.setAddress(checkInElderDto.getAddress());
            elder.setIdCardNationalEmblemImg(checkInElderDto.getIdCardNationalEmblemImg());
            elder.setIdCardPortraitImg(checkInElderDto.getIdCardPortraitImg());
            elder.setBedNumber(bed.getBedNumber());
            elder.setBedId(bed.getId());
            elderMapper.insert(elder);
        }else{
            elder.setName(checkInElderDto.getName());
            elder.setImage(checkInElderDto.getImage());
            elder.setIdCardNo(checkInElderDto.getIdCardNo());
            elder.setSex(checkInElderDto.getSex());
            elder.setStatus(4);   //状态（0：禁用，1:启用  2:请假 3:退住中 4入住中 5已退住）
            elder.setPhone(checkInElderDto.getPhone());
            elder.setBirthday(checkInElderDto.getBirthday());
            elder.setAddress(checkInElderDto.getAddress());
            elder.setIdCardNationalEmblemImg(checkInElderDto.getIdCardNationalEmblemImg());
            elder.setIdCardPortraitImg(checkInElderDto.getIdCardPortraitImg());
            elder.setBedNumber(bed.getBedNumber());
            elder.setBedId(bed.getId());
            elderMapper.updateById(elder);
        }

        return elder;

    }
    private void saveCheckInConfig(CheckInContractDto contractDto, Elder elder, CheckInConfigDto configDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();

        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfig.setNursingLevelId(configDto.getNursingLevelId());
        checkInConfig.setNursingLevelName(configDto.getNursingLevelName());
        checkInConfig.setFeeStartDate(configDto.getFeeStartDate());
        checkInConfig.setFeeEndDate(configDto.getFeeEndDate());
        checkInConfig.setDeposit(configDto.getDeposit());
        checkInConfig.setNursingFee(configDto.getNursingFee());
        checkInConfig.setBedFee(configDto.getBedFee());
        checkInConfig.setInsurancePayment(configDto.getInsurancePayment());
        checkInConfig.setGovernmentSubsidy(configDto.getGovernmentSubsidy());
        checkInConfig.setOtherFees(configDto.getOtherFees());

        checkInConfigMapper.insert(checkInConfig);



    }

    private CheckIn saveCheckIn(Elder elder, CheckInConfigDto configDto,List<ElderFamilyDto> elderFamilyDtoList) {
        CheckIn checkIn = new CheckIn();

        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(configDto.getStartDate());
        checkIn.setEndDate(configDto.getEndDate());
        checkIn.setNursingLevelName(configDto.getNursingLevelName());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setStatus(0);  //(0: 已入住, 1: 已退住)

        // 把家属信息转成json字符串
        String jsonStr = JSONUtil.toJsonStr(elderFamilyDtoList);
        checkIn.setRemark(jsonStr);

        checkInMapper.insert(checkIn);



        return checkIn;

    }

    private void saveContract(CheckInContractDto contractDto,Elder elder,CheckInConfigDto configDto) {
        Contract contract = new Contract();

        contract.setElderId(elder.getId());
        contract.setContractName(contractDto.getContractName());
        contract.setContractNumber("HT"+CodeGenerator.generateContractNumber());
        contract.setAgreementPath(contractDto.getAgreementPath());
        contract.setThirdPartyPhone(contractDto.getThirdPartyPhone());
        contract.setThirdPartyName(contractDto.getThirdPartyName());
        contract.setElderName(elder.getName());
        contract.setStartDate(configDto.getStartDate());
        contract.setEndDate(configDto.getEndDate());
        contract.setStatus(1);  // 状态 (0: 未生效, 1: 已生效, 2: 已过期, 3: 已失效)
        contract.setSignDate(contractDto.getSignDate());
        // contract.setTerminationSubmitter();
        // contract.setTerminationDate();
        // contract.setTerminationAgreementPath();
        contractMapper.insert(contract);

    }

}
